//
//  CWSocketByStream.m
//  paytong
//
//  Created by 王 友宏 on 10-12-30.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CWSocketByStream.h"
#import <CoreFoundation/CoreFoundation.h>
#import "RootViewController.h"

#import "CWUserRegisterInfo.h"
#import "CWOrderInfo.h"

extern RootViewController *mainViewController;

@implementation CWSocketByStream

@synthesize isConnected;

-(void)createStream:(NSString *)serverIP serverPort:(UInt32)serverPort
{
	CFReadStreamRef readStream;
	CFWriteStreamRef writeStream;
	self.isConnected = NO;
	isSending = NO;
	CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)serverIP, serverPort, &readStream, &writeStream);
	
	inputStream = (NSInputStream *)readStream;
	outputStream = (NSOutputStream *)writeStream;
	[inputStream setDelegate:self];
	[outputStream setDelegate:self];
	[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[inputStream open];
	[outputStream open];
}

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
	switch(eventCode) 
	{
		case NSStreamEventOpenCompleted:
			self.isConnected = YES;
			NSLog(@"Connected to serevr!");
			break;
		case NSStreamEventHasBytesAvailable:
            if(!recvData)
                recvData = [[NSMutableData data] retain];

            uint8_t buf[1024];
            unsigned int len = 0;
            len = [(NSInputStream *)aStream read:buf maxLength:1024];
            if(len == 1024) 
			{
                [recvData appendBytes:(const void *)buf length:len];
            } 
			else if(len == 0)
			{
				[mainViewController processPackage:recvData];
				[recvData release];
				recvData = nil;
            }
			else
			{
                [recvData appendBytes:(const void *)buf length:len];
				[mainViewController processPackage:recvData];
				[recvData release];
				recvData = nil;
			}
			break;
		case NSStreamEventHasSpaceAvailable:
			if(isSending)
			{
				const uint8_t *readBytes = (const uint8_t *)[sendData bytes];
				readBytes += sendPtr;
				int data_len = [sendData length];
				unsigned int len = 0;
				if(data_len - sendPtr >= 1024)
					len = 1024;
				else
				{
					len = data_len-sendPtr;
					[sendData release];
					isSending = NO;
				}
				uint8_t buf[len];
				(void)memcpy(buf, readBytes, len);
				len = [(NSOutputStream *)aStream write:(const uint8_t *)buf maxLength:len];
				sendPtr += len;
			}
			break;
		case NSStreamEventErrorOccurred:
			;
            NSError *theError = [aStream streamError];
			NSLog(@"Error %i: %@",[theError code], [theError localizedDescription]);
			break;
		default:
			break;
	}
}

-(void)sendData:(NSString *)sendContext
{
	while(isSending)
	{
	}
	
	NSLog(@"Send Data : %@",sendContext);
	
	sendData = [[sendContext dataUsingEncoding:NSUTF8StringEncoding] retain];
	sendPtr = 0;
	isSending = YES;
	
	const uint8_t *readBytes = (const uint8_t *)[sendData bytes];
	readBytes += sendPtr;
	int data_len = [sendData length];
	unsigned int len = 0;
	if(data_len - sendPtr >= 1024)
		len = 1024;
	else
	{
		len = data_len-sendPtr;
		[sendData release];
		isSending = NO;
	}
	uint8_t buf[len];
	(void)memcpy(buf, readBytes, len);
	len = [outputStream write:(const uint8_t *)buf maxLength:len];
	
//	NSString *showStr = [[NSString alloc] initWithBytes:buf length:len encoding:NSUTF8StringEncoding];
//	NSLog(@":::::%@",showStr);
//	[showStr release];
	
	sendPtr += len;
}

-(void)sendLogin:(NSString *)userName password:(NSString *)password
{
	NSString *context = [NSString stringWithFormat:@"LG0000|I1.00.00|%@|%@",userName,password];
	[self sendData:context];
}

-(void)sendLogout
{
	NSString *context = [NSString stringWithFormat:@"EX0000|bye"];
	[self sendData:context];
}

-(void)sendRegister:(CWUserRegisterInfo *)urInfo
{
	[self sendData:[urInfo getSendString]];
}

-(void)sendOrder1:(CWOrderInfo *)odInfo
{
	[self sendData:[odInfo getSendString]];
}

-(void)sendOrder2:(CWOrderInfo *)odInfo
{
	[self sendData:[odInfo getSendString]];
}

-(void)sendPay:(NSString *)userName cardLast6:(NSString *)cardLast6 payPassword:(NSString *)payPassword orderNo:(NSString *)orderNo amount:(NSString *)amount
{
	NSString *sendString = [NSString stringWithFormat:@"RZ0000|%@|%@|%@|%@|%@",userName,cardLast6,payPassword,orderNo,amount];
	[self sendData:sendString];
}

-(void)sendLGPawword:(NSString *)userName oldPassword:(NSString *)oldPassword newPassword:(NSString *)newPassword	//发送修改登录密码包
{
	NSString *sendString = [NSString stringWithFormat:@"PC0000|%@|%@|%@",userName,oldPassword,newPassword];
	[self sendData:sendString];
}

-(void)sendPayPassword:(NSString *)userName oldPassword:(NSString *)oldPassword newPassword:(NSString *)newPassword	//发送修改支付密码包
{
	NSString *sendString = [NSString stringWithFormat:@"PK0000|%@|%@|%@",userName,oldPassword,newPassword];
	[self sendData:sendString];
}

-(void)sendAddCard:(NSString *)userName IDNo:(NSString *)IDNo cardNo:(NSString *)cardNo bank:(NSString *)bank bankAddress:(NSString *)bankAddress		//发送增加银行卡信息包
{
	NSString *sendString = [NSString stringWithFormat:@"AC0000|%@|%@|%@|%@|%@",userName,IDNo,cardNo,bank,bankAddress];
	[self sendData:sendString];
}

-(void)sendInfo:(NSString *)userName email:(NSString *)email mobil:(NSString *)mobil phone:(NSString *)phone address:(NSString *)address code:(NSString *)code		//发送修改个人信息包
{
	NSString *sendString = [NSString stringWithFormat:@"MI0000|%@|%@|%@|%@|%@|%@",userName,email,mobil,phone,address,code];
	[self sendData:sendString];
}

-(void)dealloc
{
	if(recvData)
	{
		[recvData release];
		recvData = nil;
	}
	[inputStream close];
	[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[inputStream release];
	inputStream = nil;
	[outputStream close];
	[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[outputStream release];
	outputStream = nil;
	[super dealloc];
}

+(NSString *)getSub:(NSString *)mainStr fromStr:(NSString *)fromStr toStr:(NSString *)toStr
{
	NSRange fromRng = [mainStr rangeOfString:fromStr];
	NSRange toRng = [mainStr rangeOfString:toStr];
	
	return [mainStr substringWithRange:NSMakeRange(fromRng.location +fromRng.length, toRng.location-fromRng.location-fromRng.length)];
}

@end
